package com.example.tests.pages;

import java.util.List;

import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;

import static org.openqa.selenium.support.ui.ExpectedConditions.*;

import com.example.tests.logic.*;

public class LoginPage extends AnyPage {
	@FindBy(id = "loginform")
	private WebElement loginform;
	@FindBy(id = "username")
	private WebElement username;
	private String usernameErrorClass = "required error";
	@FindBy(name = "password")
	private WebElement password;
	private String passwordErrorClass = "required error";
	@FindBy(name = "submit")
	private WebElement submit;
	@FindBy(xpath = "//label[ @for=\"username\" ]")
	private WebElement usernameWarning;
	@FindBy(xpath = "//label[ @for=\"password\" ]")
	private WebElement passwordWarning;
	@FindBy(xpath = "//*/td[ @class=\"error\" ]")
	private WebElement loginError;

	
	public HomePage loginSuccesfullAs(String usrname,String passwd) {
		username.clear();
		username.sendKeys(usrname);
		password.clear();
		password.sendKeys(passwd);
		submit.click();
		return MyPageFactory.getPage(driver, HomePage.class);
	}
	public LoginPage loginUnsuccesfullAs(String usrname,String passwd) {
		username.clear();
		username.sendKeys(usrname);
		password.clear();
		password.sendKeys(passwd);
		submit.click();
		return MyPageFactory.getPage(driver, LoginPage.class);
	}
	public HomePage login(User userdata) {
		username.clear();
		username.sendKeys(userdata.getUsername());
		password.clear();
		password.sendKeys(userdata.getPassword());
		submit.click();
		return MyPageFactory.getPage(driver, HomePage.class);
	}
	public LoginPage login() {
	    username.clear();
	    password.clear();
	    submit.click();
	    return MyPageFactory.getPage(driver, LoginPage.class);
	}
    public boolean isErrorClassAppliedForUsername() {
    	return username.getAttribute("class").matches(usernameErrorClass);
    }
    public boolean isErrorClassAppliedForPassword() {
    	return username.getAttribute("class").matches(passwordErrorClass);
    }
    public boolean isUsernameWarningPresent() {
    	return usernameWarning.isDisplayed();
    }
    public boolean isPasswordWarningPresent() {
    	return passwordWarning.isDisplayed();
    }
	public String getLoginErrorText() {
		return loginError.getText();
	}
    @Override
	public boolean isOnThisPage() {
    	boolean result = 
    			0 < driver.findElements(By.name("loginform")).size();
    	return result;
	}
	@Override
	void tryToOpen() {
		List<WebElement> nav;
		wait_().until(elementToBeClickable(By.xpath("//div[ @class = 'center' ]/nav//a")));
		nav = driver.findElements(By.xpath("//div[ @class = 'center' ]/nav//li/a"));
		nav.get(nav.size()-1).click();
		wait_().until(alertIsPresent()).accept();
		
	}
};